<?php

namespace App\Models\Cruise;

use App\Models\BaseModel;
use App\Models\Shop\ShopModel;
use App\Models\Traits\KfSoftDeletes;
use App\Models\Traits\KfUid;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;

class CruiseCheckRectifyModel extends BaseModel
{
    use KfUid, KfSoftDeletes;

    protected $table    = 'cruise_check_rectify';
    protected $fillable = [
        'shopId',
        'cruiseCheckDetailId',
        'cruiseOrderId',
        'field',
        'status',
        'submitEndTime',
        'auditEndTime',
        'lastAuditResult',
        'lastAuditText',
        'templateType',
        'cruiseCheckCompanyId',
        'isDeleted',
    ];

    const SUBMIT_TIME_DAY = 10;
    const AUDIT_TIME_DAY  = 14;

    const STATUS_WAIT_TOTAL  = -1;
    const STATUS_WAIT_SUBMIT = 0;
    const STATUS_WAIT_AUDIT  = 1;
    const STATUS_FINISH      = 2;
    const STATUS_CLOSE       = 3;

    const STATUS_TEXT = [
        self::STATUS_WAIT_TOTAL  => '全部', // 仅筛选项，db不存在
        self::STATUS_WAIT_SUBMIT => '待整改',
        self::STATUS_WAIT_AUDIT  => '待审核',
        self::STATUS_FINISH      => '已整改',
        self::STATUS_CLOSE       => '已关闭',
    ];

    const AUDIT_RESULT_INIT = 0;
    const AUDIT_RESULT_OK   = 1;
    const AUDIT_RESULT_FAIL = 2;

    const AUDIT_TEXT = [
        self::AUDIT_RESULT_INIT => '-',
        self::AUDIT_RESULT_OK   => '合格',
        self::AUDIT_RESULT_FAIL => '不合格',
    ];

    const REPORT_RECTIFY_STATUS_NONE   = 0;    //无整改单
    const REPORT_RECTIFY_STATUS_ING    = 1;    //整改中
    const REPORT_RECTIFY_STATUS_FINISH = 2;    //已整改

    public function checkDetailRel(): HasOne
    {
        return $this->hasOne(CruiseCheckDetailModel::class, 'id', 'cruiseCheckDetailId');
    }

    /**
     * @return HasOne
     */
    public function shopRel(): HasOne
    {
        return $this->hasOne(ShopModel::class, 'id', 'shopId');
    }

    public function replyRel(): HasMany
    {
        return $this->hasMany(CruiseCheckRectifyReplyModel::class, 'cruiseCheckRectifyId', 'id');
    }

    public static function batchAdd(int $shopId, int $cruiseCheckDetailId, int $cruiseOrderId, array $fields, int $cruiseCheckCompanyId = 0): array
    {
        if (!$fields) {
            return [0, 0];
        }

        if (config('app.env') == 'qa' || config('app.env') == 'pre') {
            $submitEndTime = time() + 300;
            $auditEndTime  = time() + 300;
        } else {
            $submitEndTime = strtotime(date('Y-m-d 23:59:59')) + self::SUBMIT_TIME_DAY * 86400;
            $auditEndTime  = strtotime(date('Y-m-d 23:59:59')) + self::AUDIT_TIME_DAY * 86400;
        }

        $templateType = CruiseOrderModel::query()->where('id', $cruiseOrderId)->value('type');

        $params = [];
        foreach ($fields as $field) {
            $params[] = [
                'shopId'              => $shopId,
                'cruiseCheckCompanyId'=> $cruiseCheckCompanyId,
                'cruiseCheckDetailId' => $cruiseCheckDetailId,
                'cruiseOrderId'       => $cruiseOrderId,
                'templateType'        => $templateType,
                'field'               => $field,
                'status'              => self::STATUS_WAIT_SUBMIT,
                'submitEndTime'       => $submitEndTime,
                'auditEndTime'        => $auditEndTime,
                'lastAuditResult'     => self::AUDIT_RESULT_INIT,
                'lastAuditText'       => '',
            ];
        }

        self::batchAddData(collect($params), true);

        return [$submitEndTime, $auditEndTime];
    }

    /**
     * 未整改数据统计
     * @param int $templateType
     * @param int $status
     * @param int $startTime
     * @param int $endTime
     * @param int $isList
     * @return array
     */
    public static function getData(int $templateType, int $status, int $startTime, int $endTime = 0, int $isList = 0): array
    {
        $shopTotal       = $rectifyTotal = 0;
        $rectifyShopList = [];
        self::query()
            ->where('templateType', $templateType)
            ->where('status', $status)
            ->when(
                $startTime && !$endTime, function ($query) use ($startTime) {
                $query->where('auditEndTime', '>=', $startTime);
            }
            )
            ->when(
                $startTime && $endTime, function ($query) use ($startTime, $endTime) {
                $query->whereBetween('auditEndTime', [$startTime, $endTime]);
            }
            )
            ->when(
                $isList, function ($query) {
                $query->with(['shopRel'])->orderByDesc('createdAt');
            }
            )
            ->groupBy('shopId')
            ->get()
            ->map(
                function ($item) use ($status, &$shopTotal, &$rectifyTotal, &$rectifyShopList, $isList) {

                    // 全量的整改单
                    $rectifyModels = self::query()
                        ->where('cruiseCheckDetailId', $item->cruiseCheckDetailId)
                        ->get();

                    $rectifyModelsCount = $rectifyModels->count();

                    // 已关闭
                    $closeCount = $rectifyModels
                        ->where('status', CruiseCheckRectifyModel::STATUS_CLOSE)
                        ->count();

                    $rectifyModelsCount = $rectifyModelsCount - $closeCount;

                    // 已整改
                    $rectifyModelsDoneCount = $rectifyModels
                        ->where('status', CruiseCheckRectifyModel::STATUS_FINISH)
                        ->count();

                    // 整改率
                    $rectifyRate = $rectifyModelsDoneCount && $rectifyModelsCount ? round($rectifyModelsDoneCount * 100 / $rectifyModelsCount, 2) : 0;

                    // 未整改项
                    $rectifyCount =  $rectifyModels
                        ->where('status', $status)
                        ->count();

                    if ($rectifyRate <= 60) {
                        $shopTotal++;
                        $rectifyTotal += $rectifyCount;
                        if ($isList && count($rectifyShopList) < 20) {
                            $rectifyShopList[] = [
                                'shopCode'     => $item->shopRel && $item->shopRel->shopCode ?
                                    str_pad($item->shopRel->shopCode, 4, '0', STR_PAD_LEFT) : '',                  // 门店编号
                                'shopName'     => $item->shopRel->name ?? '',                                      // 门店名称
                                'branch'       => $item->shopRel->branch ?? '',                                    // 所属分公司
                                'auditEndTime' => $item->auditEndTime ? date('Y-m-d', $item->auditEndTime) : '',   // 整改截止时间
                                'rectifyRate'  => $rectifyRate ? $rectifyRate . '%' : 0,                           // 整改率
                            ];
                        }
                    }
                }
            );
        return [
            'shopTotal'       => $shopTotal,      // 待整改门店数据
            'rectifyTotal'    => $rectifyTotal,   // 待整改项
            'rectifyShopList' => $rectifyShopList,// 待整改门店详情
        ];

    }

    /**
     * 获取门店整改单数据
     *
     * @param int $shopId
     * @return Builder[]|Collection
     */
    public static function getRectificationList(int $shopId)
    {
        return CruiseCheckRectifyModel::query()
                                      ->where('templateType', CruiseTemplateModel::TYPE_3)
                                      ->where('status', CruiseCheckRectifyModel::STATUS_WAIT_SUBMIT)
//                                      ->where('submitEndTime', '<', time())
                                      ->where("shopId", $shopId)
                                      ->get();
    }
}
